package com.gis.visualization.config.listener;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gis.visualization.entity.FigureLocation;
import com.gis.visualization.entity.FigureLocationDesc;
import com.gis.visualization.entity.HistoryFigure;
import com.gis.visualization.entity.HistorySummary;
import com.gis.visualization.entity.vo.FigureExcelVo;
import com.gis.visualization.entity.vo.RecordFigureId;
import com.gis.visualization.service.*;
import com.gis.visualization.utils.http.HttpClientUtils;
import com.gis.visualization.utils.timeutils.TimeFormat;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

import java.io.File;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

public class FigureExcelListener extends AnalysisEventListener<FigureExcelVo> {

    private HistoryFigureService figureService;
    private FigureLocationService locationService;
    private FigureLocationDescService locationDescService;
    private HistorySummaryService summaryService;
    private OssService ossService;
    private List<String> cityList;
    private boolean isFigureSave;

    public FigureExcelListener(HistoryFigureService figureService, FigureLocationService locationService, FigureLocationDescService locationDescService, HistorySummaryService summaryService, OssService ossService) {
        this.figureService = figureService;
        this.locationService = locationService;
        this.locationDescService = locationDescService;
        this.summaryService = summaryService;
        this.ossService = ossService;
        String[] cityArray = new String[]{"长沙市", "湘潭市", "株洲市", "衡阳市", "邵阳市", "岳阳市", "常德市", "张家界市", "益阳市", "郴州市", "永州市", "怀化市", "娄底市", "湘西土家族苗族自治州"};
        cityList = Arrays.asList(cityArray);
        isFigureSave = false;
    }

    public FigureExcelListener() {
    }

    private void setFigureCity(String address, HistoryFigure historyFigure) {
        Map<String, String> lngAndLat = HttpClientUtils.getLngAndLat(address);
        String figCity = HttpClientUtils.getFigCity(lngAndLat);
        if (cityList.contains(figCity)) {
            historyFigure.setCity(figCity);
            historyFigure.setLongitude(new BigDecimal(lngAndLat.get("lng")));
            historyFigure.setLatitude(new BigDecimal(lngAndLat.get("lat")));
        }
    }

    @Override
    public void invoke(FigureExcelVo figureExcelVo, AnalysisContext analysisContext) {
        try{
        //    行的类型判断
        String forms = StringUtils.deleteWhitespace(figureExcelVo.getForms());
        if (!forms.equals("")) {
            // 读取数据 判断是人物还是地点
            if (forms.equals("figure")) { //人物
                HistoryFigure historyFigure = new HistoryFigure();
                //不允许重名的存在
                LambdaQueryWrapper<HistoryFigure> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(HistoryFigure::getFigureName,figureExcelVo.getFigureName());
                int count = figureService.count(wrapper);
                if (count>0){
                    //人物还没有存储
                    isFigureSave = false;
                    return;
                }
                //  将属性值赋给人物
                BeanUtils.copyProperties(figureExcelVo, historyFigure);
                try {
            //      时间处理
                    historyFigure.setBirthday(TimeFormat.timeStrDeal(figureExcelVo.getBirthday()));
                    historyFigure.setDeathDay(TimeFormat.timeStrDeal(figureExcelVo.getDeathDay()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                try {
                    String birthPlace = figureExcelVo.getBirthPlace();
                    String hometown = figureExcelVo.getHometown();
                    //出身地是否在湖南
                    if (StrUtil.isNotEmpty(birthPlace)) {
                        setFigureCity(birthPlace, historyFigure);
                    }
                    //籍贯是否在湖南
                    if (StrUtil.isEmpty(historyFigure.getCity()) && StrUtil.isNotEmpty(hometown)) {
                        setFigureCity(hometown, historyFigure);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (historyFigure.getAge() > 150 || historyFigure.getAge() < 0) {
                    historyFigure.setAge(0);
                }
                //判断人物总结中是否包含性别，不包含则默认设为男性
                if (!org.springframework.util.StringUtils.isEmpty(figureExcelVo.getSummary())) {
                    if (figureExcelVo.getSummary().contains("女")) {
                        historyFigure.setSex(2);
                    } else {
                        historyFigure.setSex(1);
                    }
                }

                //保存历史人物
                figureService.save(historyFigure);
                isFigureSave = true;
                //存储保存的历史人物id
                RecordFigureId.figureId = historyFigure.getId();
                //保存人物总结
                if (!org.springframework.util.StringUtils.isEmpty(figureExcelVo.getSummary())) {
                    HistorySummary summary = new HistorySummary();
                    summary.setId(RecordFigureId.figureId);
                    summary.setSummary(figureExcelVo.getSummary());
                    summaryService.save(summary);
                }
            } else if (forms.equals("location") && isFigureSave) {
                FigureLocation location = new FigureLocation();
                BeanUtils.copyProperties(figureExcelVo, location);
                //设置人物id到地点中
                location.setFigureId(RecordFigureId.figureId);
                StringBuilder description = new StringBuilder(figureExcelVo.getDescription());

                //保存地点
                try {
                    locationService.save(location);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //保存地点描述
                if (!org.springframework.util.StringUtils.isEmpty(description)) {
                    FigureLocationDesc locationDesc = new FigureLocationDesc();
                    locationDesc.setId(location.getId());
                    locationDesc.setDescription(description.toString());
                    locationDescService.save(locationDesc);
                }
                description.setLength(0);
            }
        }
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
